package cn.com.demo.p10;

import cn.com.demo.util.Utils;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.openssl.PEMWriter;

import javax.security.auth.x500.X500Principal;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.security.*;

/**
 * CertificationRequest ::= SEQUENCE {
 * certificationRequestInfo CertificationRequestInfo,
 * signature Algorithm      AlgorithmIdentifier,
 * signature                BIT STRING }
 * <p>
 * CertificationRequestInfo ::= SEQUENCE {
 * version           INTEGER,
 * subject           Name,
 * subjectPKInfo     SubjectPublicKeyInfo,
 * attributes        [0] Attributes }
 * Attributes ::= SET OF Attribute
 *
 * @author yuanzhenchao
 */
public class PKCS10CertRequestExample {

    static String DN = "cn=yzc,c=cn";

    public static PKCS10CertificationRequest generateRequest(String dn, KeyPair keyPair)
            throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
        return new PKCS10CertificationRequest(
                "SHA256WithRSAEncryption",
                new X500Principal(dn),
                keyPair.getPublic(),
                null,
                keyPair.getPrivate()
        );
    }

    public static void main(String[] args)
            throws InvalidKeyException, NoSuchAlgorithmException,
            NoSuchProviderException, SignatureException, IOException {
        KeyPairGenerator kpGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        kpGenerator.initialize(2048, Utils.createFixedRandom());
        kpGenerator.generateKeyPair();
        KeyPair pair = kpGenerator.generateKeyPair();

        PKCS10CertificationRequest request = generateRequest(DN, pair);

        PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(System.out));
        pemWriter.writeObject(request);
        pemWriter.close();
    }
}
